#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time
from Atm.conf import config
from Atm.core import accounts

def make_transaction(account_data, trans_type, amount, **kwargs):
    '''
    处理用户交易数据
    :param account_data: 用户数据
    :param trans_type:  交易类型
    :param amount:  交易金额
    :param kwargs:
    :return: 返回用户数据
    '''
    amount = float(amount)
    if trans_type in config.TRANSACTION_TYPE:
        interest = amount * config.TRANSACTION_TYPE[trans_type]['interest'] # 利息
        account_bill = {
            "consume_date": "%s" % time.strftime("%Y-%m-%d", time.localtime()),
            "id": account_data['id'],
            "consume_amount": amount,
            "consume_type": trans_type,
            "interest": interest
        }
        old_balance = account_data['balance']
        if config.TRANSACTION_TYPE[trans_type]['action'] == 'plus':
            new_balance = old_balance + amount + interest
        elif config.TRANSACTION_TYPE[trans_type]['action'] == 'minus':
            new_balance = old_balance - amount - interest
            if new_balance < 0:
                print('你的余额不足,交易失败...')
                return
        account_data['balance'] = new_balance
        accounts.dump_account(account_data)     # 将新的数据重新写入文件
        accounts.dump_bill(account_bill)    # 将消费记录写入文件
        return account_data
    else:
        print('交易类型错误...')